import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import UserShop from './UserShop'
import UserAdd from './UserAdd'
import UserRole from './UserRole'
import './userInfo.css'
import {Tabs, message, Modal, Button, Table} from 'antd'
const TabPane = Tabs.TabPane;

@inject('userStore', 'store')@observer
class UserInfo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isAdd: false,
      visible: false,
      operation: '',
      currentRoleUser: {},
      currentUserInfo: {}
    }
  }

  componentDidMount () {
    this.props.userStore.getUserList();
    this.props.userStore.getUserSearch({});
  }

  componentWillUnmount () {
    this.props.userStore.initUserInfo();
  }

  //切换tab栏（用户信息/用户门店）
  handleTabChange = (e) => {
    const {userList, shopList, getShopList, getUserShop} = this.props.userStore
    if ( e === '2' && shopList.length === 0 ) {
      getShopList();
      getUserShop({userId: userList[0].userId})
    }
  }

  //用户门店栏-选择用户
  handleChooseUser = (userId) => {
    this.props.userStore.getUserShop({
      userId: userId
    })
  }

  //用户门店栏-查找用户
  handleSearchUser = (params) => {
      this.props.userStore.getUserSearch({
          userName: params
      })
  }

  //用户门店栏-保存用户门店
  handleSaveUserShop = (params) => {
    return this.props.userStore.saveUserShop(params).then(res => {
      if(res.status === 200) {
        message.success('操作成功');
        this.props.userStore.getUserShop({
            userId: params.userId
        })
      } else {
        Modal.error({
            title: '操作失败',
            content: res.err
        });
      }
    })
  }

  //配置用户角色
  handleRoleConfig = (user) => {
    const {roleList, getRoleList, getUserRoles} = this.props.userStore;
    if(roleList.length === 0) {
      getRoleList();
    }
    getUserRoles({userId: user.userId});
    this.setState({
      visible: true,
      currentRoleUser: user
    })
  }

  //取消设置用户角色
  handleRoleCancel = () => {
    this.setState({
        visible: false
    })
  }

  //保存用户角色
  handleSaveUserRole = (params) => {
    return this.props.userStore.saveUserRoles(params).then(res=> {
      if(res.status === 200){
        this.handleRoleCancel();
        message.success('操作成功');
      } else {
        Modal.error({
            title: '操作失败',
            content: res.err
        });
      }
    })
  }

  //取消新增用户
  handleCancelCreateUser = () => {
    this.setState({
      isAdd: false,
      currentUserInfo: {}
    })
  }

  //新增用户
  handleInsertUser = () => {
    this.setState({
      isAdd: true,
      currentUserInfo: {}
    })
  }

  //编辑用户
  handleUpdateUser = (user) => {
    this.setState({
      isAdd: true,
      currentUserInfo: user
    })
  }

  //新增、修改用户
  handleCreateUser = (params) => {
    const {insertUser, updateUser, getUserList } = this.props.userStore;
    let action;
    if(params.userId) {
      action = updateUser;
    } else {
      action = insertUser;
    }
    return action(params).then(res => {
      if(res.status === 200) {
        message.success('操作成功');
        this.setState({
            isAdd: false
        })
        getUserList();
      } else {
        Modal.error({
            title: '操作失败',
            content: res.err
        });
      }
    })
  }

  handleCreateConfirm = (params) => {
    const {currentUserInfo} = this.state
    const _this = this;
    Modal.confirm({
      title: `是否确认${currentUserInfo.userId ? "修改" : "创建" }用户？`,
      onOk() {
          return _this.handleCreateUser(params)
      },
      onCancel() {},
    });
  }

  render() {
    const {userList, userSearch, userLoading, shopList, shopLoading, userShop, checkUser, currentShopUser,
           roleList, userRole, userRoleLoading, submitLoading, userSearchLoading,
           shopListTotal, userShopTotal} = this.props.userStore;
    const { isAdd } = this.state;
    const columns = [{
        title: '用户名',
        dataIndex: 'userName',
        key: 'userName',
    }, {
        title: '手机号码',
        dataIndex: 'phone',
        key: 'phone',
    }, {
        title: '邮箱账号',
        dataIndex: 'email',
        key: 'email',
    },{
        title: '上次登录IP',
        dataIndex: 'last_act_ip',
        key: 'last_act_ip',
    },  {
        title: '上次登录时间',
        dataIndex: 'last_act_time',
        key: 'last_act_time',
    }, {
        title: '操作',
        key: 'action',
        render: (text, record) =>
            <div>
                <a style={{marginRight: 10}}
                   onClick={() => this.handleUpdateUser(record)}>编辑</a>
                <a onClick={() => this.handleRoleConfig(record)}>配置角色</a>
            </div>
    }];
      return (
      <div>
        {this.props.store.collapse ?
            <h2 style={{marginBottom: 16}}>
              <Link to="/user/info">用户管理</Link>
            </h2> : null
        }
        <Tabs onChange={this.handleTabChange}>
          <TabPane tab="用户信息" key="1">
            <div>
              {isAdd ?
                <UserAdd onCancel={this.handleCancelCreateUser}
                         onSubmit={this.handleCreateConfirm}
                         checkUser={checkUser}
                         defaultValues={this.state.currentUserInfo}/> :
                <div>
                  <Button type='primary' style={{marginBottom: 10}}
                          onClick={this.handleInsertUser}>新增用户</Button>
                  <Table columns={columns}
                         dataSource={userList.slice()}
                         loading={userLoading}/>
                  <UserRole visible={this.state.visible}
                            loading={userRoleLoading}
                            submitLoading={submitLoading}
                            onCancel={this.handleRoleCancel}
                            roleList={roleList}
                            defaultValues={userRole.slice()}
                            userInfo={this.state.currentRoleUser}
                            onCreate={this.handleSaveUserRole}/>
                </div>
              }
            </div>
          </TabPane>
          <TabPane tab="用户门店" key="2" disabled={userList.length === 0}>
            <UserShop userList={userSearch.slice()}
                      shopList={shopList.slice()}
                      shopListTotal={shopListTotal}
                      userShop={userShop.slice()}
                      userShopTotal={userShopTotal}
                      loading={shopLoading}
                      searchLoading={userSearchLoading}
                      currentShopUser={currentShopUser}
                      onUserSearch={this.handleSearchUser}
                      onUserChoose={this.handleChooseUser}
                      onUserShopSave={this.handleSaveUserShop}/>
          </TabPane>
        </Tabs>
      </div>

    )
  }
}

export default UserInfo
